package com.longdaji.decoration.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.longdaji.decoration.R;
import com.longdaji.decoration.data.bean.GoodsSkuBean;
import com.longdaji.decoration.ui.bannerImage.BannerImageActivity;
import com.longdaji.decoration.utils.AppUtil;
import com.longdaji.decoration.utils.ImageUtil;
import com.longdaji.decoration.utils.NumberUtils;

import java.util.List;

/**
 * Created by liufei on 2017/11/30.
 */
public class ProductSkuDialog extends Dialog {
    private Context context;
    private GoodsSkuBean.Goods product;
    private List<GoodsSkuBean.Goods.GoodsSku> skuList;
    private Callback callback;

    private GoodsSkuBean.Goods.GoodsSku selectedSku;
    private String priceFormat;
    private String stockQuantityFormat;
    private ImageButton close;
    private TextView minus;
    private TextView plus;
    private Button submit;
    private EditText skuQuantityInput;
    private SkuSelectScrollView scrollSkuList;
    private ImageView skuLogo;
    //private TextView skuQuantity;
    private TextView skuInfo;
    private TextView skuSellingPrice;
    private TextView skuGoodName;
    private int type;

    public ProductSkuDialog(@NonNull Context context) {
        this(context, R.style.CommonBottomDialogStyle);
    }

    public ProductSkuDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, themeResId);
        this.context = context;
        initView();
    }

    private void initView() {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_product_sku, null);
        setContentView(view);
        close = view.findViewById(R.id.ib_sku_close);
        minus = view.findViewById(R.id.btn_sku_quantity_minus);
        plus = view.findViewById(R.id.btn_sku_quantity_plus);
        submit = view.findViewById(R.id.btn_submit);
        skuQuantityInput = view.findViewById(R.id.et_sku_quantity_input);
        scrollSkuList = view.findViewById(R.id.scroll_sku_list);
        skuLogo = view.findViewById(R.id.iv_sku_logo);
        skuInfo = view.findViewById(R.id.tv_sku_info);
        skuSellingPrice = view.findViewById(R.id.tv_sku_selling_price);
        skuGoodName = view.findViewById(R.id.tv_sku_good_name);
        skuLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = null;
                if (selectedSku == null || selectedSku.getGoodsSkuImg() == null) {
                    if (product != null) {
                        url = product.getImgAddress();
                    }

                } else {
                    url = selectedSku.getGoodsSkuImg();
                }

                Intent intent = BannerImageActivity.getStartIntent(context);
                intent.putExtra("image", url);
                context.startActivity(intent);
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = skuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                if (selectedSku == null) {
                    callback.onCancel(selectedSku, 0);
                } else {
                    int quantityInt = Integer.parseInt(quantity);
                    if (quantityInt > 0 && quantityInt <= selectedSku.getStock()) {
                        callback.onCancel(selectedSku, quantityInt);
                        dismiss();
                    } else {
                        Toast.makeText(getContext(), "商品数量超出库存，请修改数量", Toast.LENGTH_SHORT).show();
                    }

                }

            }
        });
        minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = skuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt > 1) {
                    String newQuantity = String.valueOf(quantityInt - 1);
                    skuQuantityInput.setText(newQuantity);
                    skuQuantityInput.setSelection(newQuantity.length());
                    updateQuantityOperator(quantityInt - 1);
                }
            }
        });
        plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = skuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity) || selectedSku == null) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt < selectedSku.getStock()) {
                    String newQuantity = String.valueOf(quantityInt + 1);
                    skuQuantityInput.setText(newQuantity);
                    skuQuantityInput.setSelection(newQuantity.length());
                    updateQuantityOperator(quantityInt + 1);
                }
            }
        });
        skuQuantityInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId != EditorInfo.IME_ACTION_DONE || selectedSku == null) {
                    return false;
                }
                String quantity = skuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return false;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt <= 1) {
                    skuQuantityInput.setText("1");
                    skuQuantityInput.setSelection(1);
                    updateQuantityOperator(1);
                } else if (quantityInt >= selectedSku.getStock()) {
                    String newQuantity = String.valueOf(selectedSku.getStock());
                    skuQuantityInput.setText(newQuantity);
                    skuQuantityInput.setSelection(newQuantity.length());
                    updateQuantityOperator(selectedSku.getStock());
                } else {
                    skuQuantityInput.setSelection(quantity.length());
                    updateQuantityOperator(quantityInt);
                }
                return false;
            }
        });
        scrollSkuList.setListener(new OnSkuListener() {
            @Override
            public void onUnselected(GoodsSkuBean.Goods.GoodsSku.Attribute unselectedAttribute) {
                selectedSku = null;
//                Glide.with(context)
//                        .load(product.getImgAddress())
//                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
//                        .placeholder(R.drawable.no_banner)
//                        .error(R.drawable.no_banner)
//                        .into(skuLogo);
                ImageUtil.loadImage(context, product.getImgAddress(), skuLogo);
                //GlideUtils.loadImage(context, product.getImgAddress(), skuLogo, null, R.drawable.no_banner, R.drawable.no_banner);
                //skuQuantity.setText(String.format(stockQuantityFormat, product.getStockQuantity()));
                String firstUnselectedAttributeName = scrollSkuList.getFirstUnelectedAttributeName();
                skuInfo.setText("请选择：" + firstUnselectedAttributeName);
                submit.setEnabled(false);
                String quantity = skuQuantityInput.getText().toString();
                if (!TextUtils.isEmpty(quantity)) {
                    updateQuantityOperator(Integer.valueOf(quantity));
                } else {
                    updateQuantityOperator(0);
                }
            }

            @Override
            public void onSelect(GoodsSkuBean.Goods.GoodsSku.Attribute selectAttribute) {
                String firstUnselectedAttributeName = scrollSkuList.getFirstUnelectedAttributeName();
                skuInfo.setText("请选择：" + firstUnselectedAttributeName);
            }

            @Override
            public void onSkuSelected(GoodsSkuBean.Goods.GoodsSku sku) {
                selectedSku = sku;
                if (sku.getGoodsSkuImg() == null) {
                    ImageUtil.loadImage(context, product.getImgAddress(), skuLogo);

                    // GlideUtils.loadImage(context, product.getImgAddress(), skuLogo, null, R.drawable.no_banner, R.drawable.no_banner);
                } else {
                    ImageUtil.loadImage(context, sku.getGoodsSkuImg(), skuLogo);

                    // GlideUtils.loadImage(context, sku.getGoodsSkuImg(), skuLogo, null, R.drawable.no_banner, R.drawable.no_banner);
                }

                List<GoodsSkuBean.Goods.GoodsSku.Attribute> attributeList = selectedSku.getAttributes();
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < attributeList.size(); i++) {
                    if (i != 0) {
                        builder.append("　");
                    }
                    GoodsSkuBean.Goods.GoodsSku.Attribute attribute = attributeList.get(i);
                    builder.append("\"" + attribute.getAttributeValue() + "\"");
                }
                skuInfo.setText("已选：" + builder.toString());

                //skuQuantity.setText(String.format(stockQuantityFormat, selectedSku.getStock()));
                submit.setEnabled(true);
                String quantity = skuQuantityInput.getText().toString();
                if (!TextUtils.isEmpty(quantity)) {
                    updateQuantityOperator(Integer.valueOf(quantity));
                } else {
                    updateQuantityOperator(0);
                }
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = skuQuantityInput.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                if (selectedSku == null) {
                    Toast.makeText(getContext(), "请选择商品规格", Toast.LENGTH_SHORT).show();
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt > 0 && quantityInt <= selectedSku.getStock()) {
                    callback.onAdded(selectedSku, quantityInt, type);
                    dismiss();
                } else {
                    Toast.makeText(getContext(), "商品数量超出库存，请修改数量", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void setData(int type, final GoodsSkuBean.Goods product, Callback callback) {
        if (product == null) {
            return;
        }
        this.product = product;
        this.skuList = product.getGoodsSku();
        this.callback = callback;
        this.type = type;

        priceFormat = context.getString(R.string.comm_price_format);
        stockQuantityFormat = context.getString(R.string.product_detail_sku_stock);

        updateSkuData();
        updateQuantityOperator(1);
    }

    private void updateSkuData() {
        switch (type) {
            case 1:
                submit.setText("加入购物车");
                break;
            case 2:
                submit.setText("预约试戴");
                break;
            case 3:
                submit.setText("立即购买");
                break;
            default:
                submit.setText("加入购物车");
                break;
        }
        skuGoodName.setText(product.getGoodsName());
        scrollSkuList.setSkuList(product.getGoodsSku());
        if (product != null && product.getGoodsSku().size() > 0) {
            selectedSku = product.getGoodsSku().get(0);
        }
        //GoodsSkuBean.Goods.GoodsSku firstSku = product.getGoodsSku().get(0);
        if (selectedSku != null && selectedSku.getGoodsSkuImg() != null) {

            ImageUtil.loadImage(context, selectedSku.getGoodsSkuImg(), skuLogo);

            //GlideUtils.loadImage(context, firstSku.getGoodsSkuImg(), skuLogo, null, R.drawable.no_banner, R.drawable.no_banner);
        } else {
            ImageUtil.loadImage(context, product.getImgAddress(), skuLogo);

            // GlideUtils.loadImage(context, product.getImgAddress(), skuLogo, null, R.drawable.no_banner, R.drawable.no_banner);

        }
        if (selectedSku.getStock() > 0) {
            //selectedSku = firstSku;
            // 选中第一个sku
            scrollSkuList.setSelectedSku(selectedSku);

            //GImageLoader.displayUrl(context, binding.ivSkuLogo, selectedSku.getMainImage());
            skuSellingPrice.setText(String.format(priceFormat, NumberUtils.formatNumber(selectedSku.getPrice())));
            //skuSellingPriceUnit.setText("/" + product.getMeasurementUnit());
            // skuQuantity.setText(String.format(stockQuantityFormat, selectedSku.getStock()));
            submit.setEnabled(selectedSku.getStock() > 0);
            List<GoodsSkuBean.Goods.GoodsSku.Attribute> attributeList = selectedSku.getAttributes();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < attributeList.size(); i++) {
                if (i != 0) {
                    builder.append("　");
                }
                GoodsSkuBean.Goods.GoodsSku.Attribute attribute = attributeList.get(i);
                builder.append("\"" + attribute.getAttributeValue() + "\"");
            }
            skuInfo.setText("已选：" + builder.toString());
        }
//        else {
//            //GImageLoader.displayUrl(context, binding.ivSkuLogo, product.getMainImage());
//            skuSellingPrice.setText(String.format(priceFormat, NumberUtils.formatNumber(product.get / 100)));
//            skuSellingPriceUnit.setText("/" + product.getMeasurementUnit());
//            skuQuantity.setText(String.format(stockQuantityFormat, product.getStockQuantity()));
//            submit.setEnabled(false);
//            skuInfo.setText("请选择：" + skuList.get(0).getAttributes().get(0).getKey());
//        }
    }

    private void updateQuantityOperator(int newQuantity) {
        if (selectedSku == null) {
            minus.setEnabled(false);
            plus.setEnabled(false);
            skuQuantityInput.setEnabled(false);
        } else {
            if (newQuantity <= 1) {
                minus.setEnabled(false);
                plus.setEnabled(true);
            } else if (newQuantity >= selectedSku.getStock()) {
                minus.setEnabled(true);
                plus.setEnabled(false);
            } else {
                minus.setEnabled(true);
                plus.setEnabled(true);
            }
            skuQuantityInput.setEnabled(true);
        }

    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 解决键盘遮挡输入框问题
        Window window = getWindow();
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        window.getDecorView().setPadding(0, 0, 0, 0);
        // KeyboardConflictCompat.assistWindow(getWindow());
        AppUtil.transparencyBar(getWindow());
    }

    public interface Callback {
        void onAdded(GoodsSkuBean.Goods.GoodsSku sku, int quantity, int type);

        void onCancel(GoodsSkuBean.Goods.GoodsSku sku, int quantity);
    }
}
